//
//  WFAddSavingsMethodViewController.m
//  WeiFang
//
//  Created by WeiFang on 2022.
//  Copyright © 2022 WeiFang. All rights reserved.
//

#import "WFAddSavingsMethodViewController.h"

#import "WFAddSavingsMethodTextCell.h"
#import "WFAddSavingsMethodDateSelectCell.h"
#import "WFAddSavingsMethodButtonCell.h"

#import <BRPickerView.h>

#import "WFSavingsMethodDetailViewController.h"

@interface WFAddSavingsMethodViewController ()

@property (copy, nonatomic) NSString *startValue;//开始值
@property (copy, nonatomic) NSString *dailyIncrease;//每天增加
@property (copy, nonatomic) NSString *startDate;//开始日期

@end

@implementation WFAddSavingsMethodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationBar.backgroundColor = [UIColor clearColor];
    [self setNavigationItemTitleViewWithTitle:@"365存钱法"];

    [self.tableView registerNib:[UINib nibWithNibName:@"WFAddSavingsMethodTextCell" bundle:nil] forCellReuseIdentifier:@"WFAddSavingsMethodTextCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WFAddSavingsMethodDateSelectCell" bundle:nil] forCellReuseIdentifier:@"WFAddSavingsMethodDateSelectCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WFAddSavingsMethodButtonCell" bundle:nil] forCellReuseIdentifier:@"WFAddSavingsMethodButtonCell"];
    
    self.tableView.frame = CGRectMake(0,self.navigationBarHeight, kScreenWidth, kScreenHeight - self.navigationBarHeight);
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

#pragma mark - cellDataSource

- (NSArray *)cellDataSource {
    
    if (!self.dataSource) {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:4];
        
        __block NSMutableArray *subarr = nil;
        __block NSDictionary *dict = nil;
                
        subarr = [NSMutableArray arrayWithCapacity:1];
        
        //开始值
        dict =  @{@"class":WFAddSavingsMethodTextCell.class,
                  @"height":@([WFAddSavingsMethodTextCell getCellFrame:[NSNumber numberWithFloat:120]]),
                  @"data":[WFAddSavingsMethodTextCellModel ittemModelWithTitle:@"开始值" content:_startValue],
                  @"delegate":@YES};
        [subarr addObject:dict];
        
        //每天增加
        dict =  @{@"class":WFAddSavingsMethodTextCell.class,
                  @"height":@([WFAddSavingsMethodTextCell getCellFrame:[NSNumber numberWithFloat:120]]),
                  @"data":[WFAddSavingsMethodTextCellModel ittemModelWithTitle:@"每天增加" content:_dailyIncrease],
                  @"delegate":@YES};
        [subarr addObject:dict];

        //an=a1+（n-1）*d
        //Sn＝n（a1＋an）／2
        
        NSInteger n = 365;
        NSInteger an = _startValue.integerValue + (n - 1) * _dailyIncrease.integerValue;
        NSInteger sn = n * (_startValue.integerValue + an) / 2;
        
        NSString *str = @"";
        if (_startValue.integerValue > 0 && _dailyIncrease.integerValue > 0) {
            str = [NSString stringWithFormat:@"￥%ld.00",sn];
        } else {
            str = @"";
        }
        
        //预计总金额
        dict =  @{@"class":WFAddSavingsMethodDateSelectCell.class,
                  @"height":@([WFAddSavingsMethodDateSelectCell getCellFrame:[NSNumber numberWithFloat:120]]),
                  @"data":[WFAddSavingsMethodDateSelectCellModel ittemModelWithTitle:@"预计总金额" content:str],
                  @"delegate":@YES};
        [subarr addObject:dict];
        
        //开始日期
        dict =  @{@"class":WFAddSavingsMethodDateSelectCell.class,
                  @"height":@([WFAddSavingsMethodDateSelectCell getCellFrame:[NSNumber numberWithFloat:120]]),
                  @"data":[WFAddSavingsMethodDateSelectCellModel ittemModelWithTitle:@"开始日期" content:_startDate],
                  @"delegate":@YES};
        [subarr addObject:dict];
        
        dict =  @{@"class":WFAddSavingsMethodButtonCell.class,
                  @"height":@([WFAddSavingsMethodButtonCell getCellFrame:[NSNumber numberWithFloat:100]]),
                  @"data":[WFAddSavingsMethodButtonCellModel ittemModelWithTitle:@"开始存钱"],
                  @"delegate":@YES};
        [subarr addObject:dict];
        
        [arr addObject:subarr];

        self.dataSource = arr;
    }
    return self.dataSource;
}

#pragma mark WFAddSavingsMethodTextCellDelegate 开始值 每天增加

- (void)addSavingsMethodTextCell:(WFAddSavingsMethodTextCell *)cell textField:(UITextField *)textField {
    if ([cell.model.title isEqualToString:@"开始值"]) {
        _startValue = textField.text;
    } else if ([cell.model.title isEqualToString:@"每天增加"]) {
        _dailyIncrease = textField.text;
    }
    
    WFAddSavingsMethodDateSelectCell *addSavingsMethodDateSelectCell = [self.tableView viewWithTag:10000];
    
    if (_startValue.integerValue > 0 && _dailyIncrease.integerValue > 0) {
        //an=a1+（n-1）*d
        //Sn＝n（a1＋an）／2
        
        NSInteger n = 365;
        NSInteger an = _startValue.integerValue + (n - 1) * _dailyIncrease.integerValue;
        NSInteger sn = n * (_startValue.integerValue + an) / 2;

        [addSavingsMethodDateSelectCell setData:@{@"data":[WFAddSavingsMethodDateSelectCellModel ittemModelWithTitle:@"预计总金额" content:[NSString stringWithFormat:@"￥%ld.00",sn]]} delegate:self];
    } else {
        [addSavingsMethodDateSelectCell setData:@{@"data":[WFAddSavingsMethodDateSelectCellModel ittemModelWithTitle:@"预计总金额" content:@""]} delegate:self];
    }
}

#pragma mark GPCurrencySelectCellDelegate 开始日期

- (void)addSavingsMethodDateSelectCell:(WFAddSavingsMethodDateSelectCell *)cell buttonAction:(UIButton *)sender {
    [self.view endEditing:YES];
    [self showDatePickerView];
}

#pragma mark WFAddSavingsMethodButtonCellDelegate 保存

- (void)addSavingsMethodButtonCell:(WFAddSavingsMethodButtonCell *)cell button:(UIButton *)sender {
    
    NSString *erro = @"";
    
    if (_dailyIncrease.integerValue < 1 || _dailyIncrease.integerValue > 1000) {
        erro = @"请输入1-1000的数值";
    }
    
    if (_startValue.integerValue < 1 || _startValue.integerValue > 1000) {
        erro = @"请输入1-1000的数值";
    }
    
    if (_startDate.length == 0) {
        erro = @"请选择时间";
    }
    
    if (_dailyIncrease.length == 0) {
        erro = @"请输入每天增加";
    }
    
    if (_startValue.length == 0) {
        erro = @"请输入开始值";
    }
    
    if (erro.length > 0) {
        [self showProgressHUD:erro];
    } else {
        UserManager *userManager = kUserManager.userManager;
        userManager.startValue = _startValue;
        userManager.dailyIncrease = _dailyIncrease;
        userManager.startDate = _startDate;
        [kUserManager saveUserData:userManager];
        
        [self gotoSavingsMethodDetailViewController];
    }
}

- (void)showDatePickerView {
    // 1.创建日期选择器
    BRDatePickerView *datePickerView = [[BRDatePickerView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 320 - self.bottomBarHeight, kScreenWidth, 320 + self.bottomBarHeight)];
    datePickerView.pickerMode = BRDatePickerModeYMD;
    datePickerView.selectValue = _startDate;
    datePickerView.title = @"选择日期";
    @weakify(self);
    datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
        @strongify(self);
        NSLog(@"选择的值：%@", selectValue);
        self->_startDate = selectValue;
        [self refreshData];
    };
    // 设置自定义样式
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:UIColorFromHex(0xFFFFFF)];
    customStyle.alertViewColor = UIColorFromHex(0xFFFFFF);
    customStyle.titleLineColor = UIColorFromHex(0xECECEC);
    customStyle.titleBarHeight = 58;
    customStyle.titleBarColor = [UIColor clearColor];
    customStyle.topCornerRadius = 10;
    
    customStyle.cancelBtnImage = [UIImage imageNamed:@"alert_close"];
    customStyle.titleTextFont = [UIFont boldSystemFontOfSize:16];
    customStyle.titleTextColor = UIColorFromHex(0x333333);
    customStyle.doneBtnImage = [UIImage imageNamed:@"alert_wc"];
    //设置 alertView 弹框视图顶部边框线颜色
    customStyle.pickerColor = [UIColor clearColor];
    customStyle.pickerTextColor = UIColorFromHex(0x999999);
    customStyle.separatorColor = [UIColor clearColor];
    customStyle.selectRowColor = UIColorFromHex(0x000000);
    customStyle.selectRowTextFont = [UIFont boldSystemFontOfSize:16];
    customStyle.selectRowTextColor = UIColorFromHex(0xFFFFFF);
    datePickerView.pickerStyle = customStyle;

    // 3.显示
    [datePickerView show];
}

#pragma mark - NSNotification

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification {
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;   //height 就是键盘的高度
    self.tableView.frame = CGRectMake(0, self.navigationBarHeight, kScreenWidth, kScreenHeight - self.navigationBarHeight - height);
}
 
//当键盘退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification {
    self.tableView.frame = CGRectMake(0, self.navigationBarHeight, kScreenWidth, kScreenHeight - self.navigationBarHeight);
}


#pragma mark - goto

- (void)gotoSavingsMethodDetailViewController {
    WFSavingsMethodDetailViewController* vc = [WFSavingsMethodDetailViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


